<?php
/**
 * TopAdmin
 * 版权所有 TopAdmin，并保留所有权利。
 * Author: TopAdmin <8355763@qq.com>
 * Date: 2021/11/16
 * cms扩展函数文件
 */

use app\common\model\Site;
use Soundasleep\Html2Text;
use think\facade\Cache;
use think\facade\Request;

include_once APP_PATH . '../addons/cms/cert.php';

function adminDomain(){
    $agent = agent();
    $grant = grant();
    if($grant['sign'] = $agent['sign'] && $grant['level'] = 3){
        $domain = $agent['domain'];
    } else {
        $domain = $grant['domain'];
    }
    return $domain;
}

function agents(){
    $agent = agent();
    $grant = grant();
    if($grant['sign'] = $agent['sign'] && $grant['level'] = 3){
        $agents['level'] = $agent['level'];
        $agents['sites'] = $agent['sites'];
        $agents['date']  = $agent['date'];
    } else {
        $agents['level'] = $grant['level'];
        $agents['sites'] = $grant['sites'];
        $agents['date']  = $grant['date'];
    }
    return $agents;
}

function tipsText(){
    return '需要授权,请联系技术';
}

//后台用当前站点
function onSite(){
    if (valid()){
        $siteId = 0;
        $userInfo = Session::get('admin');
        if($userInfo){
            $adminId = $userInfo['sites'];
            if($adminId){
                $siteId = $adminId;
            } else {
                if(Cookie::get('manageSiteId')){
                    $siteId = Cookie::get('manageSiteId');
                } else {
                    $siteId = masterSite('id'); //主站
                }
            }
        }
    }else{
        $siteId  = masterSite('id'); //主站
    }
    return $siteId;
}

function valid(){
    return true; //需要授权时删除本行
    $domain = $_SERVER['HTTP_HOST'];
    if(empower()){
        return true;
    } elseif($domain == '127.0.0.1' || $domain == 'localhost') {
        return true;
    }else{
        return false;
    }
}

function empower(){
    $adminDomain = adminDomain();
    $domain = $_SERVER['HTTP_HOST'];
    if($adminDomain){
        if(strpos($domain,$adminDomain) !== false){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

//所有站点
function allSite() {
    $sites = cache('Site');
    if(!is_array($sites) || empty($sites)){
        Cache::set('Site',null);
        $sites = Db('site')->where('status',1)->column('*','id');
        Cache::set('Site', $sites, 3600);
    }
    return $sites;
}

//默认数据源站信息
function masterSite($field) {
    //输出所有站点
    $sites = allSite();
    $site  = [];
    foreach ($sites as $v) {
        if ($v['master'] == 1) {
            $site[] = $v;
        }
    }
    return $site[0][$field];
}

function get_template_list()
{
    $results = scandir(TEMPLATE_PATH);
    $list    = [];
    foreach ($results as $name) {
        if ($name === '.' or $name === '..' or $name ==='.gitkeep') {
            continue;
        }
        if (is_file(TEMPLATE_PATH . $name)) {
            continue;
        }
        $templateDir = TEMPLATE_PATH . $name . DS;
        if (!is_dir($templateDir)) {
            continue;
        }

        $info_file = $templateDir . 'info.ini';
        if (!is_file($info_file)) {
            continue;
        }
        $info = parse_ini_file($info_file, true, INI_SCANNER_TYPED) ?: [];
        if (!isset($info['name'])) {
            continue;
        }
        $list[$name] = $info;
    }
    return $list;
}



function getTableList($fieldList = [])
{
    $htmlstr = "";
    foreach ($fieldList as $k => $v) {
        if ($v['type'] == "datetime") {
            $htmlstr .= "{ field: '" . $v['name'] . "',title: '" . $v['title'] . "',templet: function(d){ return yzn.formatDateTime(d." . $v['name'] . ") } },\n";
        }elseif ($v['type'] == "image") {
            $htmlstr .= "{ field: '" . $v['name'] . "',title: '" . $v['title'] . "',templet: yznTable.formatter.image },\n";
        } elseif ($v['type'] != "images" && $v['type'] != "files") {
            $htmlstr .= "{ field: '" . $v['name'] . "', align: 'left',title: '" . $v['title'] . "' },\n";
        }
    }
    return $htmlstr;
}
//获得Tag的URL
function getTagDir($tag)
{
    $tagdir = db('tags')->where('tag',$tag)->value('tagdir');
    return  $tagdir;
}

//通过ID获得当前站点名称
function getSiteName($id)
{
    if (!$id) {
        return '所有站';
    }
    if ($id !== 'false') {
        return false;
    } else {
        return '所有站';
    }
}

//当前碎片信息
function patch($langName, $newCache = false)
{
    if (empty($langName)) {
        return false;
    }
    $siteId = getSiteId();
    $key    = 'getLang_' . $langName . '_' . $siteId;
    //强制刷新缓存
    if ($newCache) {
        Cache::rm($key, null);
    }
    $cache = Cache::get($key);
    if ($cache === 'false') {
        return false;
    }
    if (empty($cache)) {
        $lang       = db('lang')->where(['name' => $langName])->find();
        $langId     = $lang['id'];
        $lang_data  = db('lang_data')->where(['lang_id' => $langId, 'site_id' => $siteId])->find();
        if($lang_data){
            $lang_value = $lang_data['value'];
        }else{
            $lang_value = $lang['value'];
        }
        Cache::set($key, $lang_value, 3600);
    } else {
        $lang_value = Cache::get($key);
    }
    return $lang_value;
}

//获取站点信息 后台用
function getSiteInfo($field)
{
    if (!$field) {
        return false;
    }
    $siteId = onSite();
    $sites  = allSite();
    $site   = [];
    foreach ($sites as $v) {
        if ($v['id'] == $siteId) {
            $site[] = $v;
        }
    }
    if ($site) {
        return $site[0][$field];
    } else {
        return false;
    }
}

//前端站点信息，后台用 和 getSiteInfo重复待优化
function getSite($field)
{
    $sites  = allSite();
    $siteId = getSiteId();
    $site   = [];
    foreach ($sites as $v) {
        if ($v['id'] == $siteId) {
            $site[] = $v;
        }
    }
    return $site[0][$field];
}


// 立即清除缓存
function  cleanUp(){
    $cache =  \util\File::del_dir(ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'cache');
    Cache::clear();
}

function onSiteName(){
    $userInfo = Session::get('admin');
    $siteIds  = $userInfo['sites'];

    if( 0 == Cookie::get('publishMode')) {
        if($siteIds){
            $siteName = getSiteInfo('name');
        }else{
            $siteName = '所有站';
        }
    }else{
        $siteName = getSiteInfo('name');
    }
    return $siteName;
}

/**
 * 根据内容ID和栏目ID获得内容url
 */
function showsUrl($id,$catid){
    $url = '';
    return buildContentUrl($catid, $id, $url);
}

//当前站URL
function onSiteUrl(){
    $siteId = onSite();
    $sites  = allSite();
    $site   = [];
    foreach ($sites as $v) {
        if ($v['id'] == $siteId) {
            $site[] = $v;
        }
    }
    return $site[0]['url'];
}

// 当前私有化值
function onPrivate() {
    $private = getSiteInfo('private');
    if ($private){
        $private = 1;
    } else {
        $private = 0;
    }
    return $private;
}

// 当前私有化站点ID值
function onSiteId() {
    $private = onPrivate();
    if($private){
        $siteId = onSite();
    } else {
        $siteId = 0;
    }
    return $siteId;
}

//数据调用时虚拟站点ID为默认站点ID
function dataSiteId(){
    $masterId = masterSite('id'); // 主站ID
    if (getSite('alone') == 1){
        $siteId = getSiteId();
    }else{
        $siteId = $masterId;
    }
    return $siteId;
}

//设置语言
function setLang($lang) {
    $domain = $_SERVER['HTTP_HOST'];
    $key = $domain . '_lang';
    Cache::clear();
    Cache::set($key, $lang);
}

//当前站ID
function getSiteId() {
    $key       = 'siteInfo';
    $domain    = $_SERVER['HTTP_HOST'];
    $config    = get_addon_config('cms');
    $setDomain = $config['domain']; // 设置中设置的默认域名
    $masterId  = masterSite('id'); // 主站ID
    $siteInfo  = Cache::get($key);
    $sites     = allSite();
    Cache::set('Site', $sites, 3600);
    if($siteInfo && $siteInfo['close'] == 0){
        Cookie::set('site_id','');
        Cookie::set('var','');
        Cache::set($key,'');
        return $masterId;
    }
    foreach ($sites as $key => $site){
        if ($site['domain'] != $domain){
            unset($sites[$key]);
        }
    }
    if (count($sites) <= 0){
        if ($setDomain){
            $site = Site::where('status',1)->where('domain',$setDomain)->find();
        }else{
            $site = Site::where('status',1)->find();
        }
        Cache::set($key,$site);
        return $site['id'];
    }else{
        if (count($sites)>1){
            if (Cookie::get('site_id') && !empty($sites[Cookie::get('site_id')])){
                if (!isset($siteInfo['id']) || $siteInfo['id'] != Cookie::get('site_id')){
                    Cache::set($key,$sites[Cookie::get('site_id')]);
                }
                return Cookie::get('site_id');
            }
        }
        $site = $sites[$masterId]?$sites[$masterId]:array_pop($sites);
        if (!isset($siteInfo['id']) || $siteInfo['id'] != $site['id']){
            Cache::set($key,$site);
        }
        return $site['id'];
    }

}

function homePage(){
    $url = onSiteUrl();
    if($url){
        $url = 'http://'.$_SERVER['HTTP_HOST'];
    } else {
        $url = '/';
    }
    return $url;
}

/*文章发布多少时间前*/
function timeRule($time)
{
    $startdate = date('Y-m-d H:i:s',$time);//时间戳转日期（要是日期的话可以不用转）
    $enddate   = date('Y-m-d H:i:s');//当前日期
    $date      = floor((strtotime($enddate) - strtotime($startdate)) / 86400);
    $hour      = floor((strtotime($enddate) - strtotime($startdate)) % 86400 / 3600);
    $minute    = floor((strtotime($enddate) - strtotime($startdate)) % 86400 % 3600 / 60);
    $second    = floor((strtotime($enddate) - strtotime($startdate)) % 86400 % 60);
    if ($date > 90)
    {
        return $startdate;
    }
    elseif ($date >= 30 && $date <= 90)
    {
        return floor($date / 30) . '个月前';
    }
    elseif ($date > 0 && $date < 30)
    {
        return $date . '天前';
    }
    elseif ($hour < 24 && $hour > 0)
    {
        return $hour . '小时前';
    }
    elseif ($minute < 60 && $minute > 0)
    {
        return $minute . '分钟前';
    }
    elseif ($second < 60 && $second > 0)
    {
        //return $second . '秒前';
        return '刚刚';
    }
}
/**
 * 删除指定标签
 * @return mixed
 */
function stripHtmlTags($str)
{

    //文字过滤参数配置
    $options = array (
        'ignore_errors' => true ,
        'drop_links' => true,
    );
    $str2= Html2Text::convert ( $str , $options);
    $data = explode(PHP_EOL,trim($str2));
    $new_data = [];
    foreach($data as $key => $value){
        $value = trim($value,'*|');
        if (!empty($value)){
            $new_data[] = $value;
        }
    }
    uasort($new_data, function ($a, $b) {
        return strLen($a) < strLen($b);
    });
    return array_unique($new_data);
}
/**
 * 还原指定标签
 * @return mixed
 */
function restoreHtmlTags($pattern,$replacement,$str)
{
    if ($pattern && is_array($pattern)){
        foreach($pattern as &$value){
            $value2 = str_replace('/','\/',$value);// /为正则特殊字符
            $value2 = str_replace(')','\)',$value2);// )为正则特殊字符
            $value2 = str_replace('(','\(',$value2);// )为正则特殊字符
            $value2 = str_replace('|','\|',$value2);// )为正则特殊字符
            $value2 = str_replace('+','\+',$value2);// )为正则特殊字符
            $value2 = str_replace('*','\*',$value2);// )为正则特殊字符
            $value2 = str_replace('?','\?',$value2);// )为正则特殊字符
            $value2 = str_replace('\'','&#39;',$value2);// )为正则特殊字符
            $value = '/'.$value2.'/';
        }
    }
    try {
//        dump($pattern);
        $new_data = preg_replace($pattern,$replacement,htmlspecialchars_decode($str));
    }catch (Exception $e){
        return ['code'=>0,'msg'=>$e->getMessage()];
    }
    return $new_data;
}